package com.eshipenet.shipnet.shiprpc.grpc;

import com.eshipenet.shipnet.ship.FindAllResult;
import com.eshipenet.shipnet.ship.grpc.*;
import com.eshipenet.shipnet.shiprpc.service.ShipOwnerService;
import com.eshipenet.shipnet.shiprpc.util.GetJObjectUtil;
import com.eshipenet.shipnet.shiprpc.util.TimestampToDate;
import com.google.protobuf.Struct;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.Timestamps;
import io.grpc.stub.StreamObserver;
import org.json4s.JsonAST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Option;
import scala.collection.immutable.List;
import squirrel.JSONQuery;

import java.util.ArrayList;
import java.util.Date;

public class ShipOwnerRepoGrpcImpl extends ShipOwnerRepoGrpc.ShipOwnerRepoImplBase {
    private Logger logger = LoggerFactory.getLogger("ShipOwnerRepoGrpcImpl");
    private ShipOwnerService service;
    public ShipOwnerRepoGrpcImpl(ShipOwnerService service) {
        this.service = service;
    }


    /**
     * 查询列表
     *
     * @param req
     * @param responseObserver
     */
    public void findAll(ShipOwnerFindAllRequest req, StreamObserver<ShipOwnerFindAllReply> responseObserver) {

        try {
            logger.info("ShipOwnerRepoGrpcImpl.findAll.Filter    {}",req.getFilter());
            ShipOwnerFindAllReply reply = findAllInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
                responseObserver.onError(e);
        }

    }


    /**
     * 创建
     *
     * @param req
     * @param responseObserver
     */
    public void createOne(ShipOwnerCreateOneRequest req, StreamObserver<ShipOwnerCreateOneReply> responseObserver) {
        try {
            logger.info("ShipOwnerRepoGrpcImpl.createOne.data   {}",req.getData());
            ShipOwnerCreateOneReply reply = createOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }

    /**
     * 修改
     *
     * @param req
     * @param responseObserver
     */
    public void updateOne(ShipOwnerUpdateOneRequest req, StreamObserver<ShipOwnerUpdateOneReply> responseObserver) {
        try {
            logger.info("ShipOwnerRepoGrpcImpl.updateOne.data   {}",req.getData());
            ShipOwnerUpdateOneReply reply = updateOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }


    /**
     * 删除
     *
     * @param req
     * @param responseObserver
     */
    public void deleteOne(ShipOwnerDeleteOneRequest req, StreamObserver<ShipOwnerDeleteOneReply> responseObserver) {
        try {
            logger.info("ShipOwnerRepoGrpcImpl.deleteOne.id  {}",req.getId());
            ShipOwnerDeleteOneReply reply = deleteOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }

    public ShipOwnerFindAllReply findAllInner(ShipOwnerFindAllRequest req) {

        int limit = req.getFilter().getLimit();
        int offset = req.getFilter().getOffset();

        if (limit == 0) {
            limit = 500;

        }
        if (offset == 0) {
            offset = 1;

        }

        //查询条件
        Struct wheres = req.getFilter().getWhere();

        JsonAST.JObject jObject = GetJObjectUtil.getWhere(wheres);

        //联合查询
        java.util.List<ShipOwnerFindAllFilterInclude> in_list = req.getFilter().getIncludeList();

        ArrayList<JsonAST.JValue> arrayList = new ArrayList<>();

        for (ShipOwnerFindAllFilterInclude include : in_list) {

            JsonAST.JValue jValue = new JsonAST.JString(include.getName());

            arrayList.add(jValue);

        }
        List<JsonAST.JValue> includes_list = scala.collection.JavaConverters.asScalaIterator(arrayList.iterator()).toList();

        JsonAST.JArray jArray = new JsonAST.JArray(includes_list);

        //生成查询列表的sql
        JSONQuery jsonQuery = JSONQuery.apply(new JsonAST.JString("ShipOwner"),
                Option.apply(jObject),
                Option.apply(new JsonAST.JString("*")),
                Option.apply(jArray),
                Option.apply(null),
                Option.apply(null));

        FindAllResult result = service.findAll(jsonQuery,limit,offset);
        //数据总数
        int totalCount = result.getTotalCount();
        //列表数据
        java.util.List<ShipOwnerEdge> list = new ArrayList<>();
        //判断是否有数据，无数据时直接返回
        if (totalCount < 1) {
            //设置分页信息
            PageInfo pageInfo = PageInfo.newBuilder()
                    .setHasNextPage(result.isHasNextPage())
                    .setHasPreviousPage(result.isHasPreviousPage())
                    .build();

            return ShipOwnerFindAllReply.newBuilder()
                    .setReq(req)
                    .addAllEdges(list)
                    .setPageInfo(pageInfo)
                    .setTotalCount(0).build();
        }

        list = result.getList();

        //设置分页信息
        PageInfo pageInfo = PageInfo.newBuilder()
                .setHasNextPage(result.isHasNextPage())
                .setHasPreviousPage(result.isHasPreviousPage())
                .setStartCursor(result.getStartCursor())
                .setEndCursor(result.getEndCursor()).build();


        return ShipOwnerFindAllReply.newBuilder()
                .setReq(req)
                .addAllEdges(list)
                .setPageInfo(pageInfo)
                .setTotalCount(totalCount).build();
    }


    public ShipOwnerCreateOneReply createOneInner(ShipOwnerCreateOneRequest req) {

        //获取当前时间
        java.sql.Timestamp createdAt = new java.sql.Timestamp(System.currentTimeMillis());
        Timestamp createdAt1 = Timestamps.fromMillis(new Date().getTime());

        Struct data = req.getData().getInfo();
        String data_str = GetJObjectUtil.getData(data);

        com.eshipenet.shipnet.ship.ShipOwner shipOwner =  new com.eshipenet.shipnet.ship.ShipOwner(
                req.getData().getName(),
                req.getData().getDesc(),
                req.getData().getAvatar(),
                data_str,
                createdAt,
                createdAt,
                req.getData().getId());

        shipOwner = service.createOne(shipOwner);

        ShipOwner ShipOwnerBuilder = com.eshipenet.shipnet.ship.grpc.ShipOwner.newBuilder()
                .setId(shipOwner.getId())
                .setName(shipOwner.getName())
                .setDesc(shipOwner.getDescription())
                .setAvatar(shipOwner.getAvatar())
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipOwner.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipOwner.getCreatedAt()))
                .setInfo(GetJObjectUtil.getData(shipOwner.getInfo()))
                .build();

        return ShipOwnerCreateOneReply.newBuilder().setData(ShipOwnerBuilder).setReq(req).build();


    }


    public ShipOwnerUpdateOneReply updateOneInner(ShipOwnerUpdateOneRequest req) {
        //获取当前时间
        java.sql.Timestamp updatedAt = new java.sql.Timestamp(System.currentTimeMillis());
        Timestamp updatedAt1 = Timestamps.fromMillis(new Date().getTime());

        Struct data = req.getData().getInfo();
        String data_str = GetJObjectUtil.getData(data);
        com.eshipenet.shipnet.ship.ShipOwner shipOwner = new com.eshipenet.shipnet.ship.ShipOwner(
                req.getData().getName(),
                req.getData().getDesc(),
                req.getData().getAvatar(),
                data_str,
                null,
                updatedAt,
                req.getData().getId()
        );

        shipOwner =  service.updateOne(req.getData().getId(),shipOwner);

        ShipOwner ShipOwnerBuilder = com.eshipenet.shipnet.ship.grpc.ShipOwner.newBuilder()
                .setId(shipOwner.getId())
                .setName(shipOwner.getName())
                .setDesc(shipOwner.getDescription())
                .setAvatar(shipOwner.getAvatar())
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipOwner.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipOwner.getCreatedAt()))
                .setInfo(GetJObjectUtil.getData(shipOwner.getInfo()))
                .build();


        return ShipOwnerUpdateOneReply.newBuilder().setData(ShipOwnerBuilder).setReq(req).build();


    }



    public ShipOwnerDeleteOneReply deleteOneInner(ShipOwnerDeleteOneRequest req) {

        com.eshipenet.shipnet.ship.ShipOwner shipOwner = service.deleteOne(req.getId());

        ShipOwner ShipOwnerBuilder = com.eshipenet.shipnet.ship.grpc.ShipOwner
                .newBuilder()
                .setId(shipOwner.getId())
                .setName(shipOwner.getName())
                .setAvatar(shipOwner.getAvatar())
                .setInfo(GetJObjectUtil.getData(shipOwner.getInfo()))
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipOwner.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipOwner.getCreatedAt()))
                .setDesc(shipOwner.getDescription())
                .build();

        return ShipOwnerDeleteOneReply.newBuilder().setData(ShipOwnerBuilder).setReq(req).build();

    }

}

